<template>
  <div class="realtime-map">
    <div class="map-header">
      <h3 class="map-title">实时用户分布</h3>
      <div class="map-status">
        <span class="status-dot"></span>
        <span class="status-text">实时监控</span>
      </div>
    </div>
    <div ref="mapRef" class="map-container"></div>
    <div class="map-legend">
      <div class="legend-item">
        <span class="legend-color" style="background: #00f0ff"></span>
        <span>活跃用户</span>
      </div>
      <div class="legend-item">
        <span class="legend-color" style="background: #00ff9d"></span>
        <span>新增用户</span>
      </div>
      <div class="legend-item">
        <span class="legend-color" style="background: #ff4757"></span>
        <span>订单量</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { regionData } from '../mock/dashboardData.js'
import chinaMapData from '../mock/china.json'

const mapRef = ref(null)
let chart = null
let updateTimer = null

// 连接线数据
const linesData = [
  { coords: [[116.46, 39.92], [121.48, 31.22]] }, // 北京-上海
  { coords: [[121.48, 31.22], [114.07, 22.62]] }, // 上海-深圳
  { coords: [[114.07, 22.62], [113.23, 23.16]] }, // 深圳-广州
  { coords: [[116.46, 39.92], [120.19, 30.26]] }, // 北京-杭州
  { coords: [[104.06, 30.67], [106.54, 29.59]] }, // 成都-重庆
]

onMounted(() => {
  initChart()
  startRealTimeUpdate()
})

onUnmounted(() => {
  if (chart) {
    chart.dispose()
  }
  if (updateTimer) {
    clearInterval(updateTimer)
  }
})

const initChart = () => {
  chart = echarts.init(mapRef.value)
  
  // 转换地图数据格式
  const mapData = regionData.map(item => ({
    name: item.name,
    value: [...item.value, item.users]
  }))


  
  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      backgroundColor: 'rgba(15, 52, 96, 0.9)',
      borderColor: '#00f0ff',
      borderWidth: 1,
      textStyle: {
        color: '#ffffff'
      },
      formatter: function(params) {
        if (params.data) {
          const cityData = regionData.find(item => item.name === params.data.name)
          if (cityData) {
            return `
              <div style="padding: 8px;">
                <div style="font-weight: bold; margin-bottom: 8px; color: #00f0ff;">${cityData.name}</div>
                <div style="margin-bottom: 4px;">👥 活跃用户: ${cityData.users.toLocaleString()}人</div>
                <div style="margin-bottom: 4px;">📦 订单数: ${cityData.orders.toLocaleString()}单</div>
                <div>💰 销售额: ¥${(cityData.revenue / 10000).toFixed(1)}万</div>
              </div>
            `
          }
        }
        return params.name
      }
    },
    // 新增visualMap配置
    visualMap: {
      min: 0,
      max: 100,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: 20,
      inRange: {
        color: ['#e0ffff', '#006edd']
      },
      textStyle: {
        color: '#fff'
      }
    },
    // 使用中国地理坐标系
    geo: {
      map: 'china',
      roam: true,
      zoom: 1.1,
      center: [104, 35],
      scaleLimit: {
        min: 0.8,
        max: 3
      },
      itemStyle: {
        areaColor: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(0, 51, 102, 0.8)'
          }, {
            offset: 1,
            color: 'rgba(0, 20, 40, 0.9)'
          }]
        },
        borderColor: 'rgba(0, 240, 255, 0.6)',
        borderWidth: 1.5,
        shadowColor: 'rgba(0, 240, 255, 0.3)',
        shadowBlur: 8
      },
      emphasis: {
        itemStyle: {
          areaColor: 'rgba(0, 240, 255, 0.2)',
          borderColor: '#00f0ff',
          borderWidth: 2,
          shadowColor: 'rgba(0, 240, 255, 0.8)',
          shadowBlur: 15
        },
        label: {
          show: true,
          color: '#00f0ff',
          fontSize: 12,
          fontWeight: 'bold'
        }
      },
      regions: [{
        name: '南海诸岛',
        itemStyle: {
          opacity: 0.3,
          areaColor: 'rgba(0, 240, 255, 0.1)'
        }
      }]
    },
    series: [
      // 数据流动线
      {
        type: 'lines',
        coordinateSystem: 'geo',
        data: linesData,
        lineStyle: {
          color: 'rgba(0, 255, 157, 0.6)',
          width: 2,
          curveness: 0.3
        },
        effect: {
          show: true,
          period: 3,
          trailLength: 0.7,
          color: '#00ff9d',
          symbolSize: 6
        },
        zlevel: 1
      },
      // 城市散点
      {
        type: 'scatter',
        coordinateSystem: 'geo',
        data: mapData,
        symbolSize: function (val) {
          return Math.max(val[2] / 800, 8)
        },
        itemStyle: {
          color: '#00f0ff',
          shadowBlur: 10,
          shadowColor: '#00f0ff'
        },
        zlevel: 2
      },
      // 重点城市效果散点
      {
        type: 'effectScatter',
        coordinateSystem: 'geo',
        data: mapData.slice(0, 5),
        symbolSize: function (val) {
          return Math.max(val[2] / 500, 15)
        },
        showEffectOn: 'render',
        rippleEffect: {
          brushType: 'stroke',
          scale: 2.5,
          period: 3
        },
        itemStyle: {
          color: '#ff4757',
          shadowBlur: 15,
          shadowColor: '#ff4757'
        },
        zlevel: 3
      },
      // 数据热力图层
      {
        type: 'heatmap',
        coordinateSystem: 'geo',
        data: mapData.map(item => [item.value[0], item.value[1], item.value[2] / 1000]),
        pointSize: 20,
        blurSize: 30,
        minOpacity: 0.2,
        maxOpacity: 0.8,
        zlevel: 1
      }
    ]
  }
  
  // 注册中国地图（使用真实数据）
  echarts.registerMap('china', chinaMapData)
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart?.resize()
  })
}

const startRealTimeUpdate = () => {
  updateTimer = setInterval(() => {
    if (!chart) return
    
    // 模拟实时数据变化
    const updatedData = regionData.map(item => ({
      ...item,
      users: item.users + Math.floor((Math.random() - 0.5) * 1000),
      orders: item.orders + Math.floor((Math.random() - 0.5) * 100),
      revenue: item.revenue + Math.floor((Math.random() - 0.5) * 50000)
    }))
    
    const mapData = updatedData.map(item => ({
      name: item.name,
      value: [...item.value, Math.max(item.users, 1000)]
    }))
    
    // 更新图表数据
    chart.setOption({
      series: [
        {
          data: linesData
        },
        {
          data: mapData
        },
        {
          data: mapData.slice(0, 5)
        },
        {
          data: mapData.map(item => [item.value[0], item.value[1], item.value[2] / 1000])
        }
      ]
    })
  }, 5000) // 每5秒更新一次
}
</script>

<style scoped>
.realtime-map {
  background: rgba(15, 52, 96, 0.3);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid rgba(0, 240, 255, 0.2);
  backdrop-filter: blur(10px);
  height: 100%;
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.map-title {
  color: #00f0ff;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.map-status {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #00ff9d;
  font-size: 12px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #00ff9d;
  animation: pulse 2s ease-in-out infinite;
}

.map-container {
  height: 400px;
  width: 100%;
}

.map-legend {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-top: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  display: block;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.5;
    transform: scale(1.2);
  }
}
</style> 